package com.example.playactivity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.remote.IMusicPlayerService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private static SeekBar sb;//进度条
    private static TextView tv_already,tv_total,tv_song_name,out;//总时长
    private Button btn_prev,btn_next;
    private ImageButton btn_play_pause;
    private IMusicPlayerService control;
    private Timer timer; // 时钟对象
    private final Activity mContext=MainActivity.this;
    public static final String ACTION = "com.example.remote.MusicPlayerService";
    private SharedPreferences mSpf;

    private ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("****", "ServiceConnection -> onServiceConnected");
            control = IMusicPlayerService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initGUI();
        mSpf = super.getSharedPreferences("musicInfo",MODE_PRIVATE);
        SharedPreferences.Editor  editor = mSpf.edit();

        out.setText("上次打开时间:"+mSpf.getString("lastOpen","")
                +"\n上次关闭时间:"+mSpf.getString("lastClose","")
                +"\n上次曲目:"+mSpf.getString("songName","")
                +"\n已播放时长:"+mSpf.getString("tv_already",""));

        SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
        sdf.applyPattern("yyyy-MM-dd HH:mm:ss");// a为am/pm的标记
        Date date = new Date();// 获取当前时间
//        System.out.println("现在时间：" + sdf.format(date)); // 输出已经格式化的现在时间（24小时制）
        editor.putString("lastOpen",sdf.format(date));
        editor.commit();
    }
    public void initGUI(){
        sb=findViewById(R.id.sb);
        tv_already=findViewById(R.id.tv_already);
        tv_total=findViewById(R.id.tv_total);
        tv_song_name=findViewById(R.id.tv_song_name);
        out=findViewById(R.id.out);
        btn_prev=findViewById(R.id.btn_prev);
        btn_next=findViewById(R.id.btn_next);
        btn_play_pause=findViewById(R.id.btn_play_pause);
//        btn_exit=findViewById(R.id.btn_exit);

        OnClick onClick = new OnClick();

        btn_prev.setOnClickListener(onClick);
        btn_next.setOnClickListener(onClick);
        btn_play_pause.setOnClickListener(onClick);
//        btn_exit.setOnClickListener(onClick);

        Intent mIntent = new Intent(ACTION);
       // Intent intent = new Intent();
        mIntent.setAction("com.example.remote.MusicPlayerService");
//        intent.setPackage("com.example.remote");
       Intent intent = new Intent(getExplicitIntent(mContext,mIntent));
       // startService(intent );
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        //进度条拖动事件
        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    try {
                        control.seekTo(progress);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                try{
                    control.pause();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                try{
                    control.resume();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    class OnClick implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_prev:
                    if(control!=null){
                        try {
                            btn_play_pause.setImageResource(R.drawable.control_pause_dark); // 切换成暂停键
                            tv_song_name.setText(control.setToPrev());
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }

                    }
                    else
                        Log.e("TAGGGG","play");
                     //播放音乐
                    timer=null;
                   // timer.cancel();

                    addTimer();

                    break;
                case R.id.btn_play_pause:
                    try {
                        tv_song_name.setText(control.getSongName());
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    // 暂停音乐
                    try {
                        Log.i("INFO", "onClick: 开始暂停按钮被点击！");

                       int flag= control.playOrPause();
                       if(flag==1 || flag==2){
                           btn_play_pause.setImageResource(R.drawable.control_pause_dark); // 切换成暂停键

                       }
                       else if(flag==3){
                           btn_play_pause.setImageResource(R.drawable.control_play_dark); // 切换成播放键

                       }
                       else {
                           Log.e("TAGGGG","flag error");

                       }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    addTimer();
                    break;
                case R.id.btn_next:
                    // 继续播放
                    try {
                        Log.i("INFO", "onClick: 切歌按钮被点击！");
                        btn_play_pause.setImageResource(R.drawable.control_pause_dark); // 切换成暂停键

                        tv_song_name.setText(control.setToNext());

                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    timer=null;
                  //  timer.cancel();

                    addTimer();
                    break;

            }

        }
    }

    @Override
    protected void onDestroy() {
        mSpf = super.getSharedPreferences("musicInfo",MODE_PRIVATE);
        SharedPreferences.Editor  editor = mSpf.edit();

        SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
        sdf.applyPattern("yyyy-MM-dd HH:mm:ss");// a为am/pm的标记
        Date date = new Date();// 获取当前时间

        editor.putString("lastClose",sdf.format(date));
        editor.putString("songName",tv_song_name.getText().toString());
        editor.putString("tv_already",tv_already.getText().toString());

        editor.commit();
//        try {
//            control.stop();
//        } catch (RemoteException e) {
//            e.printStackTrace();
//        }
        timer=null;
       // timer.cancel();
        unbindService(conn);
        super.onDestroy();
    }

//    Handler handler = new Handler(Looper.myLooper()) {
//        @Override
//        public void handleMessage(Message msg) {
//        };
//    };
//
//    private Runnable updateThread = new Runnable() {
//        @Override
//        public void run() {
//            if (control != null) {
//                try {
//                    sb.setMax(control.getDuration());
//                    sb.setProgress(control.getCurrentPosition());
//                } catch (RemoteException e) {
//                    e.printStackTrace();
//                }
//            }
//            handler.post(updateThread);
//        }
//    };
//

    public static Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData(); //获取从子线程发送过来的音乐播放进度
            int duration = bundle.getInt("duration");                  //歌曲的总时长
            int currentPostition = bundle.getInt("currentPosition");//歌曲当前进度
            sb.setMax(duration);                //设置SeekBar的最大值为歌曲总时长
            sb.setProgress(currentPostition);//设置SeekBar当前的进度位置
            String totalTime = msToMinSec(duration); // 歌曲总时长
            String currentTime = msToMinSec(currentPostition); // 歌曲当前播放时长
            tv_total.setText(totalTime);
            tv_already.setText(currentTime);
        }
    };

    public static String msToMinSec(int ms) {
        int sec = ms / 1000;
        int min = sec / 60;
        sec -= min * 60;
        return String.format("%02d:%02d", min, sec);
    }

    public void addTimer() {
        if (timer == null) {
            timer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    int duration = 0; // 获取歌曲总时长
                    try {
                        duration = control.getDuration();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    int currentPos = 0; // 获取当前播放进度
                    try {
                        currentPos = control.getCurrentPosition();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    Message msg = handler.obtainMessage(); // 创建消息对象
                    // 将音乐的总时长和播放进度封装至消息对象中
                    Bundle bundle = new Bundle();
                    bundle.putInt("duration", duration);
                    bundle.putInt("currentPosition", currentPos);
                    msg.setData(bundle);
                    // 将消息发送到主线程的消息队列
                    handler.sendMessage(msg);
                }
            };
            //开始计时任务后的5毫秒，第一次执行task任务，以后每500毫秒执行一次
            timer.schedule(task, 5, 500);
        }
    }

    //将隐式启动转换为显式启动,兼容编译sdk5.0以后版本
    public Intent getExplicitIntent(Context context,Intent implicitIntent){
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfos = pm.queryIntentServices(implicitIntent, 0);
        if (resolveInfos == null || resolveInfos.size()!= 1) {
            return null;
        }
        Intent explicitIntent = null;
        ResolveInfo info = resolveInfos.get(0);
        String packageName = info.serviceInfo.packageName;
        String className = info.serviceInfo.name;
        ComponentName component = new ComponentName(packageName,className);
        explicitIntent = new Intent(implicitIntent);
        explicitIntent.setComponent(component);
        return explicitIntent;
    }
}
